package com.zk.iotgateway.bizhandler;

import com.zk.iotgateway.dao.IotDispatchMapper;
import com.zk.iotgateway.domain.param.IotDispatchDO;
import com.zk.iotgateway.manager.GlobalManager;
import com.zk.iotgateway.rabbitmq.PublisherConfig;
import com.zk.iotgateway.util.NettyUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 *
 * netty 业务抽象类
 * @author:mn.m
 * @create 2019-07-03 下午 02:42
 **/

public abstract class AbstractIHandler implements IHandler{

    @Resource
    private IotDispatchMapper iotDispatchMapper;

    private Map<String, PublisherConfig> configMap =null;

    public   String serverPort = null;


    @Override
    public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {

    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        System.out.println("Abstracthandler is testing ");
       // handleDecode(ctx,in,out);
        System.out.println("Abstracthandler is over");
    }

    /*
    * 业务处理
    * */
    @Override
    public void handle(ChannelHandlerContext ctx, Object msg) throws Exception {

    }

   // public abstract void handleDecode(ChannelHandlerContext ctx, ByteBuf in, List out)throws Exception;

    /*
    *
    * 分发消息
    * */
    @Override
    public void dispatchMq(ChannelHandlerContext ctx, Object msg) throws Exception {
        PublisherConfig publisherConfig =null;
        String iotPort = this.returnServerPort(ctx);
        configMap= GlobalManager.MQMANAGER.get(iotPort);
        if (configMap!=null&&configMap.size()>0){
            List<IotDispatchDO> list = iotDispatchMapper.listvalidByPort(iotPort);
            for (IotDispatchDO item:list){
                publisherConfig = configMap.get(item.getId());
                publisherConfig.send(item.getExchange(),item.getRoutingKey(),msg);
            }
        }
    }

    /*
    * 获取端口
    * */
    @Override
    public String returnServerPort(ChannelHandlerContext ctx) throws Exception {
        if (StringUtils.isEmpty(serverPort)){
           serverPort = NettyUtil.returnPort(ctx);
        }
        return serverPort;
    }
}
